"use strict";
/**
 * 往微信发送消息
 * Created by liamjung on 2018/6/27.
 */
const {getMpConfig} = require("@libfintech/api-gateway-core/util/util");
const {ResponseError} = require("@libfintech/api-gateway-core/error/response_error");
const {getWechatApi} = require("@libfintech/api-gateway-core/util/wechat_api_util");
const router = require("../router/sending_router");

module.exports = async function (pipeline) {

    let req = pipeline.request;

    let sendingType = req.originalPath.substring(req.originalPath.lastIndexOf("/") + 1);
    let dto = JSON.parse(req.body);

    let mpId = dto.mpId;

    let mpConfig = await getMpConfig(mpId);

    if (!mpConfig) {
        //配置不存在时，抛出异常

        pipeline.logger.warn("mp config (mpId: " + mpId + ") not existed");

        throw new ResponseError(404);
    }

    let wechatApi = await getWechatApi(mpConfig);

    //路由到相应服务
    await router.call(wechatApi, sendingType, dto, pipeline);

    pipeline.request.host = this.host;
    pipeline.request.method = "POST";
};